//
//  LRXBlowFish.m
//  路人侠
//
//  Created by zhangxulong on 5/2/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXBlowFish.h"

@implementation LRXBlowFish
+ (NSString *)enCodeBlowfishWithValue:(NSString *)string withKeyStr:(NSString *)keyStr;
{
    NSError *error;
    NSData *key = [keyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *stringOriginal = string;
    NSData *dataOriginal = [stringOriginal dataUsingEncoding:NSUTF8StringEncoding];;
    
    
    NSData *dataEncrypted = [LRXBlowFish doBlowfish:dataOriginal
                                     context:kCCEncrypt
                                         key:key
                                     options:kCCOptionPKCS7Padding | kCCOptionECBMode
                                          iv:nil
                                       error:&error];
    
    NSString *encryptedBase64String = [dataEncrypted base64EncodedStringWithOptions:0];
    return encryptedBase64String;
}

+ (NSString *)decodeBlowCodeWithBase64Str:(NSString *)encryptedBase64String withKeyStr:(NSString *)keyStr;
{
    NSError *error;
    NSData * key = [keyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSData *dataToDecrypt = [[NSData alloc] initWithBase64EncodedString:encryptedBase64String options:0];
    NSData *dataDecrypted = [LRXBlowFish doBlowfish:dataToDecrypt
                                     context:kCCDecrypt
                                         key:key
                                     options:kCCOptionPKCS7Padding | kCCOptionECBMode
                                          iv:nil
                                       error:&error];

    NSString *stringDecrypted = [[NSString alloc] initWithData:dataDecrypted encoding:NSUTF8StringEncoding];
    return stringDecrypted;
}
+ (NSData *)doBlowfish:(NSData *)dataIn context:(CCOperation)kCCEncrypt_or_kCCDecrypt key:(NSData *)key options:(CCOptions)options iv:(NSData *)iv error:(NSError **)error;
{
    CCCryptorStatus ccStatus   = kCCSuccess;
    size_t          cryptBytes = 0;
    NSMutableData  *dataOut    = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeBlowfish];
    
    ccStatus = CCCrypt( kCCEncrypt_or_kCCDecrypt,
                       kCCAlgorithmBlowfish,
                       options,
                       key.bytes,
                       key.length,
                       (iv)?nil:iv.bytes,
                       dataIn.bytes,
                       dataIn.length,
                       dataOut.mutableBytes,
                       dataOut.length,
                       &cryptBytes);
    
    if (ccStatus == kCCSuccess) {
        dataOut.length = cryptBytes;
    }
    else {
        if (error) {
            *error = [NSError errorWithDomain:@"kEncryptionError"
                                         code:ccStatus
                                     userInfo:nil];
        }
        dataOut = nil;
    }
    
    return dataOut;
}

@end
